//音乐设备助手
//https://webfs.ali.kugou.com/202107242339/0ce998ea013f8fee52418ba0885b7500/G060/M09/00/11/HJQEAFbRRM-AVOSeADxTwivtZiI118.mp3
//f19d4c22afa7c82681321a43d50f30ce392f3ffcbceca39df35189272fc65634

function setOutAudioDevices (element, sinkId) {
    return new Promise((resolve, reject) => {
        if (typeof element.sinkId !== 'undefined') {
            element.setSinkId(sinkId)
                .then(() => {
                    console.log(`Success, audio output device attached: ${sinkId} to element with ${element.title} as source.`)
                    resolve(true)
                })
                .catch(error => {
                    let errorMessage = error
                    if (error.name === 'SecurityError') {
                        errorMessage = `You need to use HTTPS for selecting audio output device: ${error}`
                    }
                    console.error(errorMessage)
                    reject(errorMessage)
                })
        } else {
            console.warn('Browser does not support output device selection.')
        }
    })
}

let thenAudio=null;

export default {
    /**
     * 播放音乐
     * @param url 音乐地址
     * @param volume 音量，默认100
     * @param deviceId 指定的deviceId
     * @returns {Promise<void>}
     */
    playMusic(url,volume=100,deviceId){
        const audio = document.createElement('audio');
        audio.src = url;
        audio.volume=volume/100;
        audio.load()
        thenAudio=audio;
        audio.addEventListener("ended",function(){
            thenAudio=null;
        })
        if(!deviceId){
            return audio.play()
        }
        return setOutAudioDevices(audio, deviceId)
            .then(()=>{
                return audio.play()
            })
    },
    stopMusic(){
        if(thenAudio!=null){
            thenAudio.pause();
            thenAudio=null;
        }
    },
    /**
     * 获取全部声音输出设备
     * @returns {Promise<MediaDeviceInfo[]>}
     */
    getMusicMedia(){
        return navigator
            .mediaDevices
            .enumerateDevices()
            .then(x=>x.filter(x=>x.kind=="audiooutput"&&!["default","communications"].includes(x.deviceId)))
    },
    /**
     * 获取默认声音输出设备
     * @returns {Promise<MediaDeviceInfo>}
     */
    getMusicMediaDefault(){
        return navigator
            .mediaDevices
            .enumerateDevices()
            .then(x=>x.filter(x=>x.kind=="audiooutput"&&x.deviceId=="default")[0])
    },
    /**
     * 获取通讯中的设备
     * @returns {Promise<MediaDeviceInfo>}
     */
    getMusicMediaThen(){
        return navigator
            .mediaDevices
            .enumerateDevices()
            .then(x=>x.filter(x=>x.kind=="audiooutput"&&x.deviceId=="communications")[0])
    }

}
